package com.own.component.elastic.core.advanced.hook;

import co.elastic.clients.elasticsearch._types.mapping.KeywordProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import com.own.component.elastic.core.advanced.aop.ElasticFieldText;
import com.own.component.elastic.core.base.ElasticFieldHandlerEnum;
import com.own.component.elastic.core.base.hook.BaseElasticFieldHandler;
import com.own.component.elastic.property.ElasticProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * ElasticFieldTextHandler
 *
 * @author chenxueli
 * @date 2024-03-12 10:00:00
 */
@Slf4j
@Component
public class ElasticFieldTextHandler extends BaseElasticFieldHandler<ElasticFieldText> {

    @Resource
    public ElasticProperty elasticProperty;

    /**
     * 处理
     *
     * @param annotation 注解
     * @param field      字段信息
     * @return 属性
     */
    @Override
    public Property accept(ElasticFieldText annotation, Field field) {
        return Property.of(
                property -> property.text(TextProperty.of(text -> {
                    text.index(true);
                    if (annotation != null && annotation.keyword()) {
                        text.fields(Map.of("keyword", Property.of(keyword -> keyword.keyword(KeywordProperty.of(t -> t.index(true))))));
                    }
                    if (elasticProperty.getEnableIk() && annotation != null && annotation.ik()) {
                        text.analyzer(annotation.analyzer()).searchAnalyzer(annotation.searchAnalyzer());
                    }
                    return text;
                }))
        );
    }

    /**
     * 操作的名称
     *
     * @return 名称
     */
    @Override
    public ElasticFieldHandlerEnum handler() {
        return ElasticFieldHandlerEnum.TEXT;
    }

}
